package cn.xuqiudong.rpc.protocol;

import cn.xuqiudong.rpc.cluster.ClusterFacade;
import cn.xuqiudong.rpc.common.model.Invoker;
import cn.xuqiudong.rpc.common.model.XqdResponse;
import cn.xuqiudong.rpc.common.model.XqdUrl;
import cn.xuqiudong.rpc.common.util.CommonUtils;
import cn.xuqiudong.rpc.serializer.XqdSerializer;
import cn.xuqiudong.rpc.extension.XqdExtensionFactory;
import cn.xuqiudong.rpc.protocol.http.XqdHttpServer;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * 描述:基于http的通信
 * @author Vic.xu
 * @date 2022-03-04 10:09
 */
public class HttpProtocol implements Protocol {

    private static String httpProtocol = "http";

    private static String requestMethod = "POST";

    private XqdSerializer serializer = XqdExtensionFactory.defaultExtendFactory().getAdaptiveXqdExtension(XqdSerializer.class);



    /**
     * 启动tomcat服务
     * @param port port
     * @throws UnknownHostException
     */
    @Override
    public void start(int port) throws UnknownHostException {

        new XqdHttpServer(port).start();

    }

    @Override
    public Object send(Invoker invoker) throws Exception {
        XqdUrl xqdUrl = ClusterFacade.fetchUrlLoadBalance(invoker);
        URL url = new URL(httpProtocol, xqdUrl.getAddress(), xqdUrl.getPort(), "/");
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        httpURLConnection.setRequestMethod(requestMethod);
        httpURLConnection.setDoOutput(true);

        OutputStream outputStream = httpURLConnection.getOutputStream();

        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(invoker.getXqdRequest());
        oos.flush();
        oos.close();

        InputStream inputStream = httpURLConnection.getInputStream();
        byte[] bytes = CommonUtils.toByteArray(inputStream);
        //反序列化
        XqdResponse response = serializer.deserialize(bytes, XqdResponse.class);
        return response.getResultData();
    }



}
